<template>
  <BaseForm v-model="formDataModel" @close="$emit('callBack')" />

</template>

<script lang="tsx" setup>
import type { FormInstance } from 'element-plus'
import StoreInfoDetailApi from '/@/api/webPath/StoreInfoDetailApi.ts';
import { translate } from "/@/i18n";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
import StoreInfoApi from '~/src/api/webPath/StoreInfoApi';
import StoreInfoInBatchDetailApi from '~/src/api/StoreInfoInBatchDetailApi';
import StoreInfoOutBatchDetailApi from '~/src/api/StoreInfoOutBatchDetailApi';
import SupplierInfoApi from '~/src/api/webPath/SupplierInfoApi';
import { useSysDicList } from '~/src/utils/useSysDicList';
import PurchaseOrderInfoDetailApi from '~/src/api/webPath/PurchaseOrderInfoDetailApi';
defineOptions({
  name: 'StoreInfoDetailEdit',
})
const props = defineProps({
  modelValue: {

  }
})
const emit = defineEmits(['fetch-data', 'callBack'])

const formRef = ref<FormInstance>();
const title = ref<string>('');
const dialogFormVisible = ref<boolean>(false);

const storeList = ref()
const isDisabled = ref(true)
// 用于区分 出库、入库、编辑
const type = ref("")
const supplierList = ref([])
const materialCategoryList = useSysDicList("material_category")
const materialCategoryLists = useSysDicList("material_large_category")
function getSupplierTypeList() {
  StoreInfoOutBatchDetailApi.getSupplierTypeList().then(res => {
    console.log("供应商类型", res.data);
    supplierTypeList.value = res.data.map(item => ({ label: item.name, value: item.name }))
    console.log("供应商烈性2", supplierTypeList.value)
  })
}

const middleCategoryList = ref([])
const largeCategoryList = ref([])
function getLargeCategoryList() {
  StoreInfoOutBatchDetailApi.searchByType({ dicClass: 'material_large_category' }).then(res => {
    console.log("大类", res.data);
    largeCategoryList.value = res.data.map(item => ({ label: item.dicClassTypeName, value: item.dicClassTypeName }))
    console.log("大类2", largeCategoryList.value)
  })
}

const tableData = ref<any[]>([])
const supplierTypeList = ref([])


const batchDetailFields = [
  {
    divider: "批次详情"
  },
  {
    label: "",
    type: FORM_FIELD_TYPE.TABLE,
    modelData: {
      descriptionTitle: "批次详情",
      border: true,
      pagination: true,
      inline: true,
      selectable: false,
      isFullscreen: false,
      showToolbar: false,
      minWidth: '200px',
      data: {    //table  初始化
        current: 1,
        size: 10,
        total: 100,
        data: []
      },
      requestData: { api: type.value === "in" ? StoreInfoInBatchDetailApi.getPageData : StoreInfoOutBatchDetailApi.getPageData, query: { batchNo: props.modelValue!.query.batchNo } },   //数据源 参数有效性： 'steady|transient'
      columns: [

        {
          label: "批次号",
          field: "batchNo",
          width: 180,
        },

        {
          label: "入库日期",
          field: "enterDate",
          width: 200,
          fieldFormat: "date"
        },

        {
          label: "物料编码",
          field: "materialCode",
          width: 180,
        },
        {
          label: "物料名称",
          field: "materialName",
          width: 180,
        },
        {
          label: "规格",
          field: "materialSpc",
          width: 180,
        },
        {
          label: "入库数量",
          field: "num",
          width: 120,
        },
        {
          label: "当前剩余库存",
          field: "availableNum",
          width: 120,
        },

        {
          label: "供应商名称",
          field: "supplierName",
          width: 180,
        },
        {
          label: "供应商地址",
          field: "supplierAdd",
          width: 180,
        },

        {
          label: "创建时间",
          field: "create_time",
          width: 200,
        },
        {
          label: "更新时间",
          field: "update_time",
          width: 200,
        },
      ],

      actions: [
      ]


    }
  },
]
// async function remoteSearch(query: string) {
//   // TODO 更换为全量搜索基础供应商列表
//   const data = (await SupplierInfoApi.getPageData({ supplierName: query })).data.records
//   console.log("search data:", data);
//   supplierList.value = data
//   const options = data.map(item => ({
//     label: item.supplierName,
//     value: item.id

//   }))
//   console.log("options11111", options)
//   return options
// }

function updateForm(id: any, updateParam: (key: any, value: any) => void) {
  console.log("update 111111 ids:", id)
  console.log("param 111111", updateParam)
  const supplier = supplierList.value.find(x => x.id === id)
  console.log("current supplier", supplier)
  for (const key of Object.keys(toRaw(supplier))) {
    for (const { field } of formDataModel.value.items) {
      if (key === field) {
        updateParam(key, supplier[key])
      }
    }
  }
}

onMounted(async () => {
  // TODO 更换为全量获取仓库列表
  const data = (await StoreInfoApi.getPageData({})).data
  console.log("data:", data)
  storeList.value = data.records.map(item => ({ label: item.storeName, value: +item.id }))
  PurchaseOrderInfoDetailApi.getSupplierTypeList().then(res => {
    console.log("供应商类型", res.data);
    supplierTypeList.value = res.data.map(item => ({ label: item.name, value: item.name }))
    console.log("供应商烈性2", supplierTypeList.value)
  })
  // data.map(x=>{label:data})
})


const formDataModel = ref({
  columnCount: 1,
  expandLimit: 6,
  autoFit: false,
  columnWidth: '300px',
  labelPosition: 'right',
  labelWidth: '190px',
  modelData: {},  //表单参数值 初始化
  callback: async (any: object) => {  //表单执行成功后回调
    //完成数据提交

    const nowDate = new Date()
    const enterDate = `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${nowDate.getDate()} 00:00:00`
    const { smallCategory, materialCode, materialName, materialSpc, num, productDate, sampleDate, storeName, storageCondition, storagePlace, testItems, warrantyPeriod, storeId, supplierId } = any
    const storeInfoName = storeList.value.find(x => x.value === storeId).label
    const data = (await SupplierInfoApi.getPageData({ id: supplierId })).data.records
    const supplierName = data && data.length > 0 && data[0].supplierName
    if (type.value === "in") {
      const data = await StoreInfoDetailApi.batchSave({ list: [{ index: '1', enterDate, materialCategoryLevel3Name: smallCategory, materialCode, materialName, materialSpc, num, productDate, sampleDate, storeName, storageCondition, storagePlace, storeInfoName, supplierName, testItems, warrantyPeriod }] })
      if (data) {
        $baseMessage("保存成功", "success")
      }
      console.log("data", data)
    } else if (type.value === "out") {
      const data = await StoreInfoDetailApi.batchOut({ list: [{ index: '1', materialCode, materialName, materialSpc, num, storeInfoName, supplierName }] })
      if (data) {
        $baseMessage("保存成功", "success")
      }
      console.log("data", data)
    } else {
      const { message } = await StoreInfoDetailApi.save(any)
      $baseMessage(message, 'success', 'vab-hey-message-success');
    }
    dialogFormVisible.value = false

    //事件及数据推送到上一层父类
    emit('callBack', any); //把表单数据推送到上一层
  },
  items: [  //表单item数据初始化
    {
      field: "list",
      type: FORM_FIELD_TYPE.EDITABLETABLE,
      modelData: {
        data: tableData,
        // delApi: PurchaseOrderInfoDetailApi.del,
        // delParamKey: 'purchaseOrderInfoDetailIds',
        columns: [
          {
            label: "供应商类型",
            field: "supplierTypeName",
            clearable: true,
            width: "200px",
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            // defaultValue: '元',
            options: supplierTypeList,
            placeholder: "请输入",
            callback: async (v) => {
              const data = await PurchaseOrderInfoDetailApi.getPageDatas({ supplierTypeName: v })
              if (data) {
                const { data: { records } } = data
                supplierList.value = records.map(item => ({
                  label: item.supplierName,
                  value: item.supplierName
                }
                ))
                console.log("supplierList", supplierList.value)
              }
            },
            rule: [
              {
                required: true,
                message: "请选择供应商类型"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "供应商名称",
            field: "supplierName",
            clearable: true,
            width: "200px",
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            options: supplierList,
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请选择供应商"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "仓库类型名称",
            field: "storeId",
            clearable: true,
            width: "200px",
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            options: storeList,
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请选择仓库类型"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "物料编号",
            field: "materialCode",
            width: "150px",
            fixed: true,
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            config: {
              disabled: true,
            },

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "物料名称",
            field: "materialName",
            width: "150px",
            fixed: true,
            clearable: true,
            config: {
              disabled: isDisabled,
            },
            async callback(handlers, row: any, v: any) {
              const res = await StoreInfoApi.generateMaterialCode({ materialName: v })
              console.log("materialName change:", v)
              if (res) {
                handlers.updateParam("materialCode", res.data)
                console.log("material Code  ", res.data)
              }

            },
          },
          {
            label: "物料规格",
            field: "materialSpc",
            fixed: true,
            clearable: true,
            config: {
              disabled: isDisabled,
            },

            type: FORM_FIELD_TYPE.INPUT,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "大类",
            field: "largeCategory",
            clearable: true,
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            options: largeCategoryList,
            width: 120,
            placeholder: "请输入",
            callback: async (v) => {
              const data = await StoreInfoOutBatchDetailApi.searchByType({ dicClass: v })
              if (data) {
                const { data: largeCategoryList } = data
                console.log("largeCategoryList", largeCategoryList)
                middleCategoryList.value = largeCategoryList.map(item => ({ label: item.middleCategory, value: item.id }))

              }
            },
            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "亚类",
            field: "middleCategory",
            width: "150px",
            clearable: true,
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            options: middleCategoryList,
            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "细类",
            field: "smallCategory",
            fixed: true,
            clearable: true,
            disabled: isDisabled,

            options: materialCategoryList,
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "存储条件",
            field: "storageCondition",
            fixed: true,
            clearable: true,
            config: {
              disabled: isDisabled,
            },

            type: FORM_FIELD_TYPE.INPUT,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "存储地点",
            field: "storagePlace",
            fixed: true,
            clearable: true,
            config: {
              disabled: isDisabled,
            },

            type: FORM_FIELD_TYPE.INPUT,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "检测项目",
            field: "testItems",
            fixed: true,
            clearable: true,
            config: {
              disabled: isDisabled,
            },

            type: FORM_FIELD_TYPE.INPUT,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "第三方检测报告中样品名称",
            field: "sampleName",
            fixed: true,
            clearable: true,
            config: {
              disabled: isDisabled,
            },

            type: FORM_FIELD_TYPE.INPUT,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "第三方检测报告日期",
            field: "sampleDate",
            fixed: true,
            clearable: true,
            props: {
              disabled: isDisabled,
              valueFormat: "YYYY-MM-DD hh:mm:ss"
            },

            type: FORM_FIELD_TYPE.DATE,

            placeholder: "请输入",

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "食材名称",
            field: "foodName",
            width: "150px",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请输入食材名称"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "入库日期",
            width: "180px",
            field: "purchaseDate",
            type: FORM_FIELD_TYPE.DATE,
            defaultValue: `${new Date().getFullYear()}-${(new Date().getMonth() + 1).toString().padStart(2, '0')}-${(new Date().getDate()).toString().padStart(2, '0')}`,
            rule: [
              {
                required: true,
                message: "请输选择入库日期"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "入库数量",
            field: "num",
            width: "180px",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            placeholder: "请输入",
            callback: (handlers, formData, value: any) => {
              if (formData["unitPrice"]) {
                handlers.updateParam("totalPrice", +value * +formData["unitPrice"])
              }
            },
            rule: [
              {
                required: true,
                message: "请输入入库数量"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]

          },
          {
            label: "入库单位",
            field: "unit",
            clearable: true,
            width: "150px",
            type: FORM_FIELD_TYPE.INPUT,
            defaultValue: '公斤',
            placeholder: "请输入",

            rule: [
              {
                required: true,
                message: "请输入入库单位"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]

          },
          {
            label: "单价",
            field: "unitPrice",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            width: "100px",
            placeholder: "请输入",
            callback: (handlers, formData, value: any) => {
              if (formData["num"]) {
                handlers.updateParam("totalPrice", +value * +formData["num"])
              }
            },
            rule: [
              {
                required: true,
                message: "请输入单价"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "单价单位",
            field: "priceUnit",
            clearable: true,
            width: "120px",
            type: FORM_FIELD_TYPE.INPUT,
            defaultValue: '公斤/元',
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请输入单价单位"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "物料总价",
            field: "totalPrice",
            clearable: true,
            width: "100px",
            type: FORM_FIELD_TYPE.INPUT,
            config: {
              disabled: true,
            },
            placeholder: "自动计算",

            // value: totalPrice.value,

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "物料总价单位",
            field: "totalPriceUnit",
            clearable: true,
            width: "120px",
            type: FORM_FIELD_TYPE.INPUT,
            defaultValue: '元',
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请输入总价单位"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },


        ]

      }
    },
    // {
    //   label: "大类",
    //   field: "largeCategory",
    //   fixed: true,
    //   clearable: true,
    //   disabled: isDisabled,

    //   options: materialCategoryLists,
    //   type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // {
    //   label: "中类",
    //   field: "middleCategory",
    //   fixed: true,
    //   clearable: true,
    //   disabled: isDisabled,

    //   options: materialCategoryList,
    //   type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },

    // {
    //   label: "小类",
    //   field: "smallCategory",
    //   fixed: true,
    //   clearable: true,
    //   disabled: isDisabled,
    //   options: materialCategoryList,
    //   type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // // {
    // //   label: "物料类别",
    // //   field: "smallCategory",
    // //   fixed: true,
    // //   clearable: true,
    // //   disabled: isDisabled,

    // //   options: materialCategoryList,
    // //   type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,

    // //   placeholder: "请输入",

    // //   rule: {
    // //     trigger: 'blur',
    // //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    // //       callback();
    // //     },
    // //   },

    // // },
    // {
    //   label: "存储条件",
    //   field: "storageCondition",
    //   fixed: true,
    //   clearable: true,
    //   config: {
    //     disabled: isDisabled,
    //   },

    //   type: FORM_FIELD_TYPE.INPUT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // {
    //   label: "存储地点",
    //   field: "storagePlace",
    //   fixed: true,
    //   clearable: true,
    //   config: {
    //     disabled: isDisabled,
    //   },

    //   type: FORM_FIELD_TYPE.INPUT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // {
    //   label: "检测项目",
    //   field: "testItems",
    //   fixed: true,
    //   clearable: true,
    //   config: {
    //     disabled: isDisabled,
    //   },

    //   type: FORM_FIELD_TYPE.INPUT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // {
    //   label: "第三方检测报告中样品名称",
    //   field: "sampleName",
    //   fixed: true,
    //   clearable: true,
    //   config: {
    //     disabled: isDisabled,
    //   },

    //   type: FORM_FIELD_TYPE.INPUT,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // {
    //   label: "第三方检测报告日期",
    //   field: "sampleDate",
    //   fixed: true,
    //   clearable: true,
    //   props: {
    //     disabled: isDisabled,
    //     valueFormat: "YYYY-MM-DD hh:mm:ss"
    //   },

    //   type: FORM_FIELD_TYPE.DATE,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },
    // {
    //   label: computed(() => type.value === "out" ? "出库数量" : type.value === "in" ? "入库数量" : "库存量"),
    //   field: "num",
    //   fixed: true,
    //   clearable: true,
    //   type: FORM_FIELD_TYPE.INPUTNUMBER,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },

  ],
})






//页面数据加载
onMounted(async () => {
  getSupplierTypeList()
  getLargeCategoryList()
  console.log("query", props.modelValue.query)

  type.value = props.modelValue.query?.type

  // if (!props.modelValue.query.storeInfoDetailId) {
  //   formDataModel.value.items = formDataModel.value.items.filter(x => x.fixed)
  // } else {
  //   formDataModel.value.items.push(formDataModel.value.items.filter(x => x.fixed), ...batchDetailFields)
  // }
  //初始化数据model
  if (props.modelValue.query) { //跳转过来时候有参数
    if (props.modelValue.query.storeInfoDetailId) {  //id存在则为编辑，加载网络数据，如上级页面带参数手动覆盖

      const { data } = await StoreInfoDetailApi.getDetail({
        storeInfoDetailId: props.modelValue.query.storeInfoDetailId   //从路由中获取参数
      })

      if (["in", "out"].includes(type.value)) {
        isDisabled.value = true
        const { num, ...rest } = data
        formDataModel.value.modelData = { num: 0, ...rest }
      } else {
        isDisabled.value = false
        formDataModel.value.modelData = data
      }
    } else {
      //新增时候则用父类页面传参默认填充可根据业务修改
      for (const key in props.modelValue.query) {
        formDataModel.value.modelData[key] = props.modelValue.query[key]
      }
      isDisabled.value = false
    }
  }
})


//方法暴露区域  todo
defineExpose({

})

</script>
